

var _ = {
    conf: {},
};

var lazy_embed = function (options) {
    window.lazy_embed_data = options;
    if ($('body').data('binded')) {
        $(window).hashchange();
        return;
    }
    lazy_include({
        jsFiles: [{
            url: "/js/cultivateWeb/resourceJquery.js",
            cb: function () {
                $('body').data('binded', true);
                $(window).hashchange(function () {
                    var opts = window.lazy_embed_data;

                    var url = opts.url;
                    if (window.location.hash) {
                        url = window.location.hash.substr(1);

                        if (url.indexOf('?') == 0) {
                            if (opts.url.indexOf('?') == -1)
                                url = opts.url + url;
                            else
                                url = opts.url + '&' + url.substr(1);
                        }
                    }

                    jQuery.ajax({
                        headers: {
                            'embed': '1',
                            'embedUrl': (opts.affect_url || ''),
                            'usedinmvc': opts.usedinmvc
                        },
                        dataType: 'json',
                        url: url,
                        success: function (data) {
                            //data = handleException(data);

                            opts.container.empty().html(data);

                            if (opts.callback && jQuery.isFunction(opts.callback)) {
                                opts.callback.apply();
                            }
                        },
                        error: function () {}
                    });
                });

                $(window).hashchange();
            }
        }],
        cssFiles: []
    });
};

$.extend({
    htmlencode: function (text) {
        return $('<div />').text(text).html();
    },
    htmldecode: function (text) {
        return $('<div />').html(text).text();
    }
});

/**
 * 全局过滤html编码
 */
object_htmlencode = function (obj) {
    if (!obj) {
        return obj;
    }

    if (typeof (obj) == 'string') {
        return $.htmlencode(obj);
    }

    if ($.isArray(obj)) {
        $.each(obj, function (i, v) {
            obj[i] = object_htmlencode(v);
        });

        return obj;
    }

    if (typeof (obj) == 'object') {
        for (var key in obj) {
            obj[key] = object_htmlencode(obj[key]);
        }
    }

    return obj;
};

// // 全局拦截 http request、response
// $.ajaxSetup({
//     beforeSend: function (xhr) {

//     },
//     dataFilter: function (data, type) {
//         if ((type || '').toLowerCase() == 'json') {
//             data = JSON.stringify(object_htmlencode(JSON.parse(data)));
//         }

//         return data;
//     },
// });

window.alert = function (message, type) {
    $.pnotify({
        title: message,
        addclass: "stack-modal",
        delay: 5000,
        sticker: false,
        stack: {
            "dir1": "down",
            "dir2": "right",
            "push": "top",
            "modal": true,
            "overlay_close": true,
            "context": $("body")
        },
        type: type || 'info'
    });
};

/**
 * @name 获取地址栏中的参数
 * @return Object
 */
window.getQuery = function (key) {
    var arr = [],
        obj = {},
        location = window.location.href,
        has = location.indexOf('?') > -1,
        isHash = location.indexOf('#');

    if (!has) return null;
    arr = location.substring(location.indexOf('?') + 1, isHash > -1 ? isHash : location.length).split('&');

    for (var i = 0, len = arr.length; i < len; i++) {
        var temp = arr[i].split('=');
        if (temp.length) obj[temp[0]] = temp[1].replace(/#/g, '');
    }

    if (key) {
        return obj[key];
    } else {
        return obj;
    }
};

/*
 *JS文件动态加载工具
 */
var LazyInclude = {
    scripts: [],
    loadScript: function (url, callback) {
        var script = this.scripts[url] || (this.scripts[url] = {
            loaded: false,
            callbacks: []
        });

        if (script.loaded) {
            return callback.apply();
        }

        script.callbacks.push({
            fn: callback
        });
        if (script.callbacks.length == 1) {
            $.ajax({
                type: 'GET',
                url: url,
                dataType: 'script',
                cache: true,
                success: function () {
                    script.loaded = true;
                    $.each(script.callbacks, function () {
                        this.fn.apply();
                    });
                    script.callbacks.length = 0;
                },
                error: function (xhr, status, errorMsg) {
                    if (window.console) {
                        console.log('lazyIncludeError:' + errorMsg + ',statusCode:' + status);
                        throw errorMsg;
                    } else {
                        alert('lazyIncludeError:' + errorMsg + ',statusCode:' + status);
                        throw errorMsg;
                    }
                }
            });
        }
    },
    call: (function () {
        function hasFile(tag, url) {
            var contains = false;
            var type = (tag == "script") ? "src" : "href";

            $(tag + '[' + type + ']').each(function (i, v) {
                var attr = $(v).attr(type)
                if (attr == url || decodeURIComponent(attr).indexOf(url) != -1) {
                    contains = true;
                    return false;
                }
            });

            return contains;
        }

        function loadCssFile(files) {
            var urls = files && typeof (files) == "string" ? [files] : files;

            for (var i = 0; i < urls.length; i++) {
                if (!hasFile("link", urls[i])) {
                    var ele = document.createElement("link");
                    ele.setAttribute('type', 'text/css');
                    ele.setAttribute('rel', 'stylesheet');
                    ele.setAttribute('href', urls[i]);

                    document.getElementsByTagName('head')[0].appendChild(ele);
                }
            }
        }

        function loadScript(files) {
            if (!$.isArray(files)) {
                return LazyInclude.loadScript(files.url, files.cb);
            }

            var counter = 0;

            // parallel loading
            return $.each(files, function (i, v) {
                LazyInclude.loadScript(v.url, v.cb);
            });
        }

        function includeFile(opts) {
            //首先加载css
            loadCssFile(opts.cssFiles);
            //加载js
            loadScript(opts.jsFiles);
        }
        return {
            include: includeFile
        };
    })()
};

var lazy_include = function (opts) {
    LazyInclude.call.include(opts);
};

String.prototype.ltrim = function (r) {
    return this.replace(/^\s*/gi, '').replace(new RegExp('^' + r), '');
};

String.prototype.rtrim = function (r) {
    return this.replace(/\s*$/gi, '').replace(new RegExp(r + '$'), '');
};

String.prototype.format = function () {
    var args = arguments,
        args1 = {};
    if (args.length == 0) return this;
    if (typeof args[0] == 'object') args1 = args[0];
    return this.replace(/\{([\w]+)\}/g, function ($1, $2) {
        return args1[$2] || args[$2] || $1;
    });
};

String.prototype.QueryStringToJSON = function () {
    if (this.length == 0 || this.indexOf('=') == -1) {
        return {};
    }
    try {
        var json = {};

        var str = ("'" + this.replace(/([\?&])([^&=\s]*)=/g, "$1$2':'").replace(/&{2,}/g, "&").replace(/(^\?)|(&$)/g, "").replace(/&/g, "','") + "'").replace(/'.*?':'.*?'/g, function (r) {
            var obj = eval('({' + r + '})');
            for (var key in obj) {
                if (json[key]) {
                    json[key] = json[key] + ',' + obj[key];
                } else {
                    json[key] = obj[key];
                }
            }
        });

        return json;
    } catch (error) {
        return {};
    }
};

String.prototype.trimStart = function (trimStr) {
    if (!trimStr) {
        return this;
    }
    var temp = this;
    while (true) {
        if (temp.substr(0, trimStr.length) != trimStr) {
            break;
        }
        temp = temp.substr(trimStr.length);
    }
    return temp.toString();
};

String.prototype.trimEnd = function (trimStr) {
    if (!trimStr) {
        return this;
    }
    var temp = this;
    while (true) {
        if (temp.substr(temp.length - trimStr.length, trimStr.length) != trimStr) {
            break;
        }
        temp = temp.substr(0, temp.length - trimStr.length);
    }
    return temp.toString();
};

_.obj2query = function (obj) {
    var str = '';
    for (var key in obj) {
        str += '&' + key + '=' + obj[key];
    }
    return str.ltrim('&');
};

_.width = function () {
    var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
    if ($.browser.msie && $.browser.version < 8) {
        if (document.compatMode == 'CSS1Compat') {
            pageWidth = document.documentElement.clientWidth;
        } else {
            pageWidth = document.body.clientWidth;
        }
    }
    return pageWidth;
};

_.height = function () {
    var pageHeight;
    if (document.compatMode == 'CSS1Compat') {
        pageHeight = document.documentElement.clientHeight;
    } else {
        pageHeight = document.body.clientHeight;
    }
    return pageHeight;
};

_.resize = function () {};

_.changeHashPage = function (strhash) {
    return strhash.replace(/page=\d+/i, "page=1");
};

_.get = function (el, container, table_html, pageIndex, events, isContain) {
    if (!pageIndex || pageIndex < 1) {
        pageIndex = 1;
    }
    container = container || "#container";
    table_html = table_html || "table_html";
    var params = "?page=" + pageIndex;
    var form_page = $('[name=page]', el);
    if (form_page.length) {
        params = '';
        form_page.val(pageIndex);
    }
    var action = el.attr("action");
    var url = action + params;
    el.attr('action', url);
    el.submit_form(function (r) {
        if (!r || (r.code && r.code < 0)) {
            return false;
        }
        if (isContain) {
            $(container, el).html(template(table_html, r));
        } else {
            $(container).html(template(table_html, r));
        }
        var _el = $("#" + el.attr("id"));
        _pagination(r.pagination, _el, "", container, table_html, events, isContain);
    });
    el.attr('action', action);
    return false;
};

_pagination = function (pagination, el, pageType, container, table_html, events, isContain) {
    // 不满足分页条件提前返回
    _.hash = ('?' + location.hash.substring(1)).QueryStringToJSON();

    // 缓存当前页面数据
    var currentHashPage = _.hash.page = (_.hash.page && isNaN(_.hash.page * 1) ? 1 : _.hash.page * 1) || 1;

    var paginationWrap = $(".pagination", el);
    var pages = Math.ceil(pagination.totalCount / pagination.pageSize) ? Math.ceil(pagination.totalCount / pagination.pageSize) : 1;

    // 修正地址栏hash里的page和计算的最大页不匹配

    /*执行行内方法*/
    if (events && $.isFunc(events)) {
        events.apply(this, [el]);
    }
    _.checkAll($("table", el));
    _.hoverTr($("table", el));

    $("select[name=pageSize]", el).change(function () {
        /*add by lixx*/
        _.ajaxPagination(1, el, pageType, container, table_html, events, isContain);
        return false;
    });

    // 满足渲染分页大小
    // 但不满足分页条件
    if (pages == 1 && pagination.totalCount > 10) {
        drawPageSizePicker(pagination.pageNumber, pageType);
        return false;
    }

    // 页面数只有1页的时候不再渲染分页
    if (pages <= 1) {
        return false;
    }

    // 默认情况下为hash
    // 移除page，组合分页跳转link
    delete _.hash.page;

    var hashQuery = _.obj2query(_.hash);
    var searchQuery = _.obj2query(_.url);

    var hrefTextPrefix = '#' + (!hashQuery ? 'page=' : hashQuery + '&page=');
    var selectOnClick = true;

    _.hash.page = currentHashPage;

    var onPageClickCallback = function (pageNumber, event, pageType) {
        _.hash.page = pageNumber;
        drawPageSizePicker(pageNumber, pageType);
    };

    if (pageType == 'search') {
        var currentSearchPage = _.url.page = (_.url.page && isNaN(_.url.page * 1) ? 1 : _.url.page * 1) || 1;
        delete _.url.page;
        hrefTextPrefix = '?' + (!searchQuery ? 'page=' : searchQuery + '&page=');
        _.url.page = currentSearchPage;

        onPageClickCallback = function (pageNumber, event) {
            _.url.page = pageNumber;
        }
    } else if (pageType == 'ajax') {
        selectOnClick = false;
        var form = el.parents('.ui-dialog').find("form:first");
        if (form.length == 0) {
            return false;
        }

        onPageClickCallback = function (pageNumber, event) {
            var data = ("?" + decodeURIComponent(form.serialize().replace(/\+/g, " "), true)).QueryStringToJSON();
            data.page = pageNumber;
            var url = form.attr("action");

            _.ajax(url, data, function (r) {
                /*调用common.js中的方法_.ajaxPagination*/
                //_.ajaxPagination(r);
            }, "json");

            return false;
        };
    }

    var instance = $(".pagination", el).pagination({
        items: pagination.totalCount,
        itemsOnPage: pagination.pageSize,
        currentPage: pagination.pageIndex,
        pageType: pageType,
        selectOnClick: selectOnClick,
        hrefTextPrefix: hrefTextPrefix,
        cssStyle: 'light-theme',
        prevText: '上一页',
        nextText: '下一页',
        onPageClick: onPageClickCallback
    });
    drawPageSizePicker(pagination.pageIndex, pageType);

    function drawPageSizePicker(pageNumber, pageType) {
        if (pageType != "no-jump") {
            $('.pagination ul', el).append('<div style="display: inline-block;">到<input type="text" class="pageInput" style="width: 25px; margin: 0px 10px; vertical-align: middle; margin-bottom: 3px;" value="' + pageNumber + '" />页<a href="javascritpt:;" class="pageChange" style="display: inline-block; background: #009999; color: #fff; margin: 0px 10px;">确定</a></div>');
        }
    };

    $(".pagination ul .pageInput", el).keyup(function () {
        var value = $(this).val().replace(/[^\d]/g, '');
        $(this).val(value);
    });

    $(".pagination ul .pageInput", el).keypress(function (e) {
        if (e.which == 13) {
            var pageIndex = $(this).parents(".paging:first").find(".pageInput").val();
            pageIndex = pageIndex > pages ? pages : (pageIndex > 0 ? pageIndex : 1);
            _.ajaxPagination(pageIndex, el, pageType, container, table_html, events, isContain);
            return false;
        }
    });

    $(".pageChange", el).on("click", function () {
        var pageIndex = $(this).parents(".paging:first").find(".pageInput").val();
        pageIndex = pageIndex > pages ? pages : (pageIndex > 0 ? pageIndex : 1);
        _.ajaxPagination(pageIndex, el, pageType, container, table_html, events, isContain);
        return false;
    });

    $(".page-link", el).on("click", function () {
        var pageIndex = $(this).data("pageindex");
        _.ajaxPagination(pageIndex, el, pageType, container, table_html, events, isContain);
        return false;
    });
};

/*分页后请求返回后，需要执行的方法*/
_.ajaxPagination = function (pageIndex, el, pageType, container, table_html, events, isContain) {
    if (!pageIndex || pageIndex < 1) {
        pageIndex = 1;
    }
    container = container || "#container";
    table_html = table_html || "table_html";
    var params = "?page=" + pageIndex;
    var form_page = $('[name=page]', el);
    if (form_page.length) {
        params = '';
        form_page.val(pageIndex);
    }
    var action = el.attr("action");
    var type = el.attr("method");
    var url = action + params;
    //location.href = url;
    el.attr('action', url);
    el.submit_form(function (r) {
        var _el = el.attr("id") ? $("#" + el.attr("id")) : el;
        if (isContain) {
            $(container, _el).html(template(table_html, r));
        } else {
            $(container).html(template(table_html, r));
        }

        _el = el.attr("id") ? $("#" + el.attr("id")) : el;
        _pagination(r.pagination, _el, pageType, container, table_html, events, isContain);
    });
    el.attr('action', action);
    return false;
};

_.getContainsHtml = function (data) {
    $.ajax({
        type: data.type || "post",
        url: data.url,
        cache: data.cache || true,
        timeout: data.timeout || 30000,
        data: data.data || {},
        dataType: data.dataType || "json",
        beforeSend: data.beforeSend || function () {},
        success: function (r) {
            if (!r) {
                alert("页面请求超时，请检查网络设置");
            } else {
                // r = object_htmlencode(r);
                data.success(r);
            }
        },
        complete: data.complete || function () {
            $('.loading').hide();
        },
        error: data.error || function (XMLHttpRequest, status, errorThrown) {
            if (status == 'timeout' || status == 'error') {
                alert(errorThrown);
            }
        }
    });

    return false;
};

$(window).resize(function () {
    _.resize();
    return false;
});

template.helper('get_item', function (str, index, devision) {
    if (!str) {
        return str;
    }
    devision = devision ? devision : ',';
    var arr = str.split(devision);
    if (arr.length < index + 1) {
        return "";
    } else {
        return arr[index];
    }
});

template.helper('dateFormat', function (date, format) {
    if (date == 0)
        date = new Date();
    else if (date.indexOf("/Date(") > -1) {
        var date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "") - 8 * 60 * 60 * 1000, 10));
    } else
        date = new Date(date);

    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
});

template.helper('timeFormat', function (timeValue) {
    var result = "";
    if (!timeValue) {
        result = "---";
        return result;
    };
    var sTime = parseInt(timeValue); /*秒*/
    var mTime = 0; /*分*/
    var hTime = 0; /*时*/
    if (sTime > 60) {
        mTime = parseInt(sTime / 60);
        sTime = parseInt(sTime % 60);
        if (mTime > 60) {
            hTime = parseInt(mTime / 60);
            mTime = parseInt(mTime % 60);
        }
    }
    result = sTime + "秒";
    if (mTime > 0) {
        result = mTime + "分" + sTime + "秒";
    }
    if (hTime > 0) {
        result = hTime + "小时" + mTime + "分" + sTime + "秒";
    }
    return result;
});

template.helper("subString", function (str, start, end) {
    str = (str) ? $('<div />').append(str).html() : ""
    if (str.length > end)
        return str.substring(start, end) + "...";
    else
        return str;

    var x = str;
});

template.helper("subString_html", function (str, start, end) {
    var s = $.htmldecode($.htmldecode(str));
    if (s.length > end) {
        return s.substring(start, end) + "...";
    } else {
        return s;
    }
});

template.helper("htmlEncode", function (text) {
    return $.htmlencode(text);
    // return text;
});

template.helper("htmlDecode", function (text) {
    $.htmldecode($.htmldecode(text));
});

template.helper('contains', function (str, substr) {
    return str.indexOf(substr);
});

template.helper('contains_s', function (str, substr) {
    return str.indexOf(substr) == -1 ? '' : 'selected';
});

template.helper('b2other', function (str) {
    var val = parseInt(str);

    var Units = new Array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");

    var i = 0;
    while ((val / 1024).toFixed(2) > 1) {
        val /= 1024;
        i++;
    }
    return val.toFixed(2) + Units[i];
});

template.helper('empty', function (obj, key) {
    return obj ? eval('obj.' + key) : '';
});

template.helper('tofixed', function (str, num, percent) {
    return (str * percent).toFixed(num);
});

/*根据阿拉伯数字获取对呀的中文汉字*/
template.helper('num2hanzi', function (num) {
    var chinas = new Array("", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "百", "零");
    var nums = new Array(1000);
    for (var i = 1; i < 1000; i++) {
        var b = parseInt(i / 100);
        var s = parseInt(i / 10)

        var str = chinas[b] + chinas[b == 0 ? 0 : 11] + chinas[s % 10] +
            chinas[s % 10 == 0 ? 12 : 10] + chinas[i % 10];
        str = str.trimStart('零').trimEnd('零');
        if (i >= 10 && i < 20) str = str.trimStart('一');

        nums[i - 1] = str;
    }
    return nums[num];
});

/*根据索引获取选项序号*/
template.helper('num2zimu', function (num) {
    var englishs = new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "-");
    return englishs[num];
});

template.helper('isvideo', function (str) {
    var temp = false;
    if (!str) {
        return temp;
    }
    var lastindex = str.lastIndexOf('.') + 1;
    var type = str.substring(lastindex, str.length);
    switch (type) {
        case "mp4":
        case "flv":
        case "swf":
        case "asf":
        case "avi":
        case "mpg":
        case "wav":
        case "rm":
        case "rmvb":
        case "wmv":
            temp = true;
            break;
        default:
            break;
    }
    return temp;
});

template.helper('indent', function (count, value) {
    return Array(count).join(' ') + value;
});

template.helper('now', function () {
    var nowStr = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/-/g, '/');
    return nowStr; /*获取时间*/
});

template.helper('dateCompare', function (startDateStr, endDateStr, type) {
    var sDate = new Date(startDateStr); /*时间1*/
    var eDate = new Date(endDateStr); /*时间2*/
    var result; /*比较结果*/
    if (sDate.getTime() == eDate.getTime()) {
        result = 0; /*时间1==时间2*/
    } else if (sDate.getTime() < eDate.getTime()) {
        result = 1; /*时间1<时间2*/
    } else {
        result = 2; /*时间1>时间2*/
    }
    switch (type) {
        case "==":
            /*时间1==时间2？*/
            return result == 0 ? true : false;
        case "<":
            /*时间1<时间2？*/
            return result == 1 ? true : false;
        case ">":
            /*时间1>时间2？*/
            return result == 2 ? true : false;
        case "<=":
            /*时间1<=时间2？*/
            return result != 2 ? true : false;
        case ">=":
            /*时间1>=时间2*/
            return result != 1 ? true : false;
        default:
            return false;
    }
});

template.helper('isContainsString', function (bigString, smallString, devision) {
    devision = devision ? devision : ',';
    if (!bigString || bigString.length == 0)
        return false;
    var bigStringArr = bigString.split(devision);
    for (var i = 0; i < bigStringArr.length; i++) {
        var innerString = bigStringArr[i];
        if ($.trim(innerString) == $.trim(smallString)) {
            return true;
        }
    }
    return false;
});

/*sns中判断是否选择了该选项*/
template.helper('optionIsChecked', function (myOptionList, optionId) {
    for (var i = 0; i < myOptionList.length; i++) {
        if (myOptionList[i] == optionId) {
            return true;
        }
    }
    return false;
});

template.helper('checkSpace', function (questionAnswer, studentAnswer, sortOrder) {
    if (questionAnswer.length == 0 || studentAnswer.length == 0)
        return false;
    var answerList = questionAnswer.Split(',');
    var currentAnswer = answerList[order];
    currentAnswer = currentAnswer.Replace(" ", "").Replace("’", "'").Replace("‘", "'").Replace("＇", "'").Replace("\t", "").Replace("\n", "").Replace("；", ";").Replace("，", ",").ToUpper();
    studentAnswer = studentAnswer.Replace(" ", "").Replace("’", "'").Replace("‘", "'").Replace("＇", "'").Replace("\t", "").Replace("\n", "").Replace("；", ";").Replace("，", ",").ToUpper();
    if (currentAnswer == studentAnswer)
        return true;
    return false;
});

template.helper('getSplitAnswer', function (answerString, index) {
    var answerArr = answerString.split(',');
    return answerArr[index];
});

template.helper('getAnswerArr', function (answerString) {
    var answerArr;
    if (!answerString) {
        answerArr = [26, 26, 26, 26]
    } else {
        answerArr = answerString.split(',');
        for (var j = 0; j < answerArr.length; j++) {
            if (answerArr[j] == -1) {
                answerArr[j] = 26;
            }
        }
    }
    return answerArr;
});

template.helper('getpipeiOption', function (answerList, type) {
    var answerData = answerList[0];
    if (answerData) {
        if (type == 1) {
            return answerData.OptionContent ? answerData.OptionContent.split(',') : "";
        } else if (type == 2) {
            return answerData.OptionSelectContent ? answerData.OptionSelectContent.split(',') : "";
        } else {
            return answerData.OptionAnswerContent ? answerData.OptionAnswerContent.split(',') : "";
        }
    }
});

template.helper('relativeTime', function (date) {
    if (date == 0)
        date = new Date();
    else if (date.indexOf("/Date(") > -1) {
        var date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "") - 8 * 60 * 60 * 1000, 10));
    } else
        date = new Date(date);

    var _now = new Date();
    var now_Y = _now.getFullYear(),
        now_D = _now.getDay();

    var Y = date.getFullYear(),
        M = date.getMonth() + 1,
        D = date.getDay(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    if (M < 10) {
        M = '0' + M;
    };
    if (D < 10) {
        D = '0' + D;
    };
    if (H < 10) {
        H = '0' + H;
    };
    if (m < 10) {
        m = '0' + m;
    };
    if (s < 10) {
        s = '0' + s;
    };
    var nowTime = _now.getTime();
    var oldTime = date.getTime();

    if (nowTime < oldTime) {
        return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
    }
    var delta_T = nowTime - oldTime;
    var T_Years = parseInt(delta_T / 31536000000),
        T_Days = parseInt(delta_T / 86400000),
        T_Hours = parseInt(delta_T / 3600000),
        T_Minutes = parseInt(delta_T / 60000),
        T_Seconds = parseInt(delta_T / 1000);
    if (delta_T >= 31536000000) {
        return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
    } else if ((365 >= T_Days) && (T_Days > 1)) {
        if (now_Y != Y) {
            /*说明已经跨年*/
            return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
        } else {
            return M + '月' + D + '日 ' + H + ':' + m;
        }
    } else if (T_Days == 1) {
        return "昨天 " + H + ':' + m;
    } else if (now_D != D) {
        /*说明跨天了*/
        return "昨天 " + H + ':' + m;
    } else if (T_Minutes >= 10) {
        return H + ':' + m;
    } else if ((10 > T_Minutes) && (T_Minutes >= 1)) {
        return T_Minutes + '分钟前';
    } else {
        return "刚刚";
    }
});

template.helper('getItem', function (arry, num) {
    var item;
    if (!arry) {
        return null;
    } else if (arry.length > num) {
        item = arry[num];
    }
    return item;
});

_.isEmptyObject = function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
};

_.url = location.search.QueryStringToJSON();
_.hash = ('?' + location.hash.substring(1)).QueryStringToJSON();
_.token = $.cookie("auth");
_.authorization =  $.cookie("authorization");
//if (location.pathname.indexOf("portal.html") == -1 && !_.token) { location.href = '/portal/portal.html'; }

_.ajax = function () {
    $('.loading').show();
    var args = arguments;
    if (typeof (args[0]) == 'string') {
        var data = {
            url: args[0]
        };
        if (typeof (args[1]) == 'object') {
            data.data = args[1];
            if (typeof (args[2]) == 'function') {
                data.success = args[2];
            }
            if (typeof (args[3]) == 'function') {
                data.error = args[3];
            }
            if (typeof (args[4]) == 'function') {
                data.error = args[4];
            }
            if (typeof (args[3]) == 'string' && args[3] == "get") {
                data.type = args[3];
            }
            if (typeof (args[4]) == 'string') {
                data.type = args[4];
            }
        } else if (typeof (args[1] == 'function')) {
            data.success = args[1];
            if (typeof (args[2]) == 'function') {
                data.error = args[2];
            }
        }
    }

    if (typeof (args[0]) == 'object') {
        data = args[0];
    }

    return $.ajax({
        type: data.type || "post",
        url: data.url,
        cache: data.cache || true,
        timeout: 30000,
        headers: {'Authorization': _.authorization},
        data: data.data ? data.data : {},
        dataType: data.dataType || "json",
        beforeSend: data.beforeSend || function () {},
        success: function (r) {
            if (!r) {
                //window.location.href = "/portal/portal.html";
            } else {
                // r = object_htmlencode(r);
                data.success(r);
            }
        },
        complete: data.complete || function () {
            $('.loading').hide();
        },
        error: data.error || function (XMLHttpRequest, status, errorThrown) {
            if (status == 'timeout' || status == 'error') {
                /*alert(errorThrown);*/
            }
        }
    });
};

_.ajaxadd = function () {
    $('.loading').show();
    var args = arguments;
    if (typeof (args[0]) == 'string') {
        var data = {
            url: args[0]
        };
        if (typeof (args[1]) == 'object') {
            data.data = args[1];
            if (typeof (args[2]) == 'function') {
                data.success = args[2];
            }
            if (typeof (args[3]) == 'function') {
                data.error = args[3];
            }
        } else if (typeof (args[1] == 'function')) {
            data.success = args[1];
            if (typeof (args[2]) == 'function') {
                data.error = args[2];
            }
        }
    }

    if (typeof (args[0]) == 'object') {
        data = args[0];
    }

    return $.ajax({
        type: data.type || "post",
        url: data.url,
        cache: data.cache || true,
        timeout: data.timeout,
        data: !_.isEmptyObject(data.data) ? $.extend(data.data, _.hash) : !_.isEmptyObject(_.hash) ? _.hash : !_.isEmptyObject(_.url) ? _.url : "",
        dataType: data.dataType || "json",
        beforeSend: data.beforeSend || function () {},
        success: function (r) {
            // r = object_htmlencode(r);
            data.success(r);
        },
        complete: data.complete || function () {
            $('.loading').hide();
        },
        error: data.error || function (XMLHttpRequest, status, errorThrown) {
            if (status == 'timeout' || status == 'error') {
                /* alert(errorThrown);*/
            }
        }
    });
};

_.selected = function () {
    $('#queryform input,#queryform select').each(function (i, v) {
        $(v).val(decodeURI(eval('_.hash.' + $(v).attr('name')) || ''));
    });
}

_.css = function (url) {
    $("head").append('<link rel="stylesheet" href="{0}"'.format(url));
};

_.script = function (url, success) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.onload = success;
    head.appendChild(script);
};

/* 缓存之前加载过的不再重新加载*/
_.cache = {};
_.include = function (data) {
    var cache = _.cache;

    if (data.cssFiles) {
        $.isArray(data.cssFiles) ? $.each(data.cssFiles, function (i, v) {
            cache[v] ? cache[v] : (cache[v] = true) && _.css(v);
        }) : (cache[data.cssFiles] ? cache[data.cssFiles] : (cache[data.cssFiles] = true) && _.css(data.cssFiles));
    }

    if (data.jsFiles) {
        $.isArray(data.jsFiles) ? $.each(data.jsFiles, function (i, v) {
            cache[v.url] ? v.cb() : (cache[v.url] = true) && _.script(v.url, v.cb);
        }) : (cache[data.jsFiles.url] ? data.jsFiles.cb() : (cache[v.url] = true) && _.script(data.jsFiles.url, data.jsFiles.cb));
    }
};

_.checkAll = function (table) {
    //全选或全不选
    $('.checkall', table).click(function () {
        if ($(this).is(':checked')) {
            $('.checkbox', table).not(':disabled').attr('checked', true);
        } else {
            $('.checkbox', table).attr('checked', false);
        }
    });

    //同步全选框
    $('.checkbox', table).click(function () {
        var objs = $('tbody .checkbox', table).not(':disabled');
        $('.checkall', table).attr('checked', objs.length == objs.filter(':checked').length);
    });
};

_.hoverTr = function (table) {
    $("tr", table).hover(function () {
        $(this).toggleClass("active")
    });
};

_.getSelectedRowIds = function (table) {
    var ids = [];
    $.each($("tbody tr td:first-child :checkbox[checked]", table), function (i, v) {
        ids.push(encodeURIComponent($(this).parents('tr:first').attr('id')));
    });
    return ids;
};

/*create by wl deal with checkbox data*/
_.dealData = function (selecteddata, data, type) {
    var idIndex;
    data += ",";
    if (type == "append") {
        idIndex = ("," + selecteddata).indexOf("," + data);
        if (idIndex < 0) {
            selecteddata += data;
        }
    } else {
        var idLen = data.length;
        idIndex = ("," + selecteddata).indexOf("," + data);
        if (idIndex >= 0) {
            var idSubPre = selecteddata.substring(0, idIndex);
            var idSubSuf = selecteddata.substring(idIndex + idLen);
            selecteddata = idSubPre + idSubSuf;
        }
    }
    return selecteddata;
};

/* 合理显示图片宽高 */
_.imgOnloadHandler = function () {
    if (!(this instanceof HTMLImageElement)) {
        return false;
    }

    if (this.complete) {
        if (this.naturalHeight > this.naturalWidth) {
            this.style.width = "auto";
            this.style.height = "100%";
        } else if (this.naturalHeight < this.naturalWidth) {
            this.style.height = "auto";
            this.style.width = "100%";
        }
    } else {
        this.onLoad = _.imgOnloadHandler;
    }
};

_.imgOnload = function (ctx) {
    _.imgOnloadHandler.call(ctx);
};


$(function () {
    /*$.pnotify.defaults.styling = "jqueryui";
    $.pnotify.defaults.history = false;
    $.pnotify.defaults.animation = "none";
    $.pnotify.defaults.sticker = false;*/

    /*预览共公方法，如果将所有的带有data-preview_url_ueditor直接预览*/
    $(document).off("click.preview").on("click.preview", "[data-preview_url_ueditor]", function () {
        var _this = $(this);
        download = _this.data("download"),
            //previewUrl = _this.data("preview_url_ueditor"),
            previewUrl = _this.attr("data-preview_url_ueditor"),
            title = _this.data("title");

        _.ajax(urls2.Ueditor_Preview_Url, {
            url: previewUrl,
            title: title
        }, function (r) {
            if (!r || r.code < 0) {
                alert(r.msg || "发生未知错误");
                return false;
            }
            _.include({
                jsFiles: [{
                    url: "/common/js/dfs/preview.js",
                    cb: function () {
                        var dlg = jQuery.dynamic_dialog("dlg_preview_resource");
                        var html = "";
                        if (!download || download == "0")
                            html = '<div style="height:450px;" id="preview_container"></div>';
                        else
                            html = '<a  href="' + r.downloadUrl + '" target="_blank" class="am-btn am-btn-primary" style="float: right;">下载</a><div style="height:450px;    margin-top: 40px;" id="preview_container"></div>';
                        dlg.html(html).dialog({
                            title: "预览资源",
                            width: 900,
                            heigth: 450,
                            draggable: true,
                            modal: false,
                            close: function () {
                                $("#preview_container").html("");
                            }
                        });
                        $('#preview_container').DViewer({
                            data: r.url,
                            baseUrl: '/common/js/dfs/'
                        });
                    }
                }],
                cssFiles: []
            });
        }, 'json');
        return false;
    });

    window.checkInputValueRequired = function (input) {
        if (input.length <= 0) {
            return true;
        }
        if ($.trim(input.val()) == '') {
            input.addClass('am-field-error');
            window.wxc.xcConfirm("字段不能为空！", window.wxc.xcConfirm.typeEnum.error);
            return false;
        } else {
            input.removeClass('am-field-error');
        }
        return true;
    };

    var ueditor_setting_defaults = {
        initialFrameHeight: 200,
        wordOverFlowMsg: '<span style="color:red;">你输入的字符个数已经超出最大允许值！！</span>',
        autoFloatEnabled: true,
        topOffset: 0,
        toolbars: [
            [
                'source', '|', 'undo', 'redo', 'fontfamily', 'link', 'spechars',
                'bold', 'italic', 'underline', '|', 'fontsize', '|', 'kityformula', 'choosefile'
            ]
        ]
    };

    $.extend({
        autoCut: function (text, cut_length, end) {
            if (text.length == 0 || cut_length > $.getLength(text)) return $.htmlencode(text);

            var result = '';
            var j = 0;

            var str_array = text.split('');

            for (var i = 0; i < str_array.length; i++) {
                var c = str_array[i];

                if (text.charCodeAt(i) >= 255) {
                    j = j + 2;
                } else {
                    j = j + 1;
                }

                result = result + c;

                if (j >= cut_length) {
                    if (end) return $.htmlencode(result + end);
                    else return $.htmlencode(result + '...');
                }
            }
        },

        bindUeditor: function (identity, opts, bIsHideFile) {
            var toolbarsArr = [
                [
                    'source', '|', 'undo', 'redo', 'fontfamily', 'link', 'spechars',
                    'bold', 'italic', 'underline', '|', 'fontsize', '|', 'kityformula', 'choosefile'
                ]
            ];
            if (bIsHideFile) //学生作答客观题页面隐藏选择文件按钮
            {
                toolbarsArr = [
                    [
                        'source', '|', 'undo', 'redo', 'fontfamily', 'link', 'spechars',
                        'bold', 'italic', 'underline', '|', 'fontsize', '|', 'kityformula'
                    ]
                ];
            }
            var ueditor_setting_defaults = {
                initialFrameHeight: 200,
                wordOverFlowMsg: '<span style="color:red;">你输入的字符个数已经超出最大允许值！！</span>',
                autoFloatEnabled: true,
                topOffset: 0,
                toolbars: toolbarsArr
            };

            window.UEDITOR_HOME_URL = "/common/js/ueditor/";
            opts = $.extend(false, {}, ueditor_setting_defaults, opts);
            editor = UE.getEditor(identity, opts);

            /*var old_getActionUrl = editor.getActionUrl;*/
            editor.getActionUrl = function (action) {
                if (action == 'config') return '/common/js/ueditor/config.aspx';
                return action;
            };
            return editor;
        },

        getLength: function (text) {
            var length = 0,
                c = '';

            for (var i = 0; i < text.length; i++) {
                c = text.charCodeAt(i);
                if (c >= 255) {
                    length = length + 2;
                } else {
                    length = length + 1;
                }
            }
            return length;
        },

        dynamic_dialog: function (selector) {
            var dialog = $('#' + selector);

            if (dialog.length == 0) {
                $('body').append($('<div id="' + selector + '" />'));
                return $('#' + selector);
            }

            return $('#' + selector);
        }
    });
});

/*
 * 功能：美化alert和confirm
 * 使用说明:
 * window.wxc.Pop(popHtml, [type], [options])
 * popHtml:html字符串
 * type:window.wxc.xcConfirm.typeEnum集合中的元素
 * options:扩展对象
 * 用法:
 * 1. window.wxc.xcConfirm("我是弹窗<span>lalala</span>");
 * 2. window.wxc.xcConfirm("成功","success");
 * 3. window.wxc.xcConfirm("请输入","input",{onOk:function(){}})
 * 4. window.wxc.xcConfirm("自定义",{title:"自定义"})
 */
(function ($) {
    return; /*暂时注释*/
    window.wxc = window.wxc || {};
    window.wxc.xcConfirm = function (popHtml, type, options) {
        var btnType = window.wxc.xcConfirm.btnEnum;
        var eventType = window.wxc.xcConfirm.eventEnum;
        var popType = {
            info: {
                title: "提示信息",
                icon: "0 0", //蓝色i
                btn: btnType.ok
            },
            success: {
                title: "成功",
                icon: "0 -48px", //绿色对勾
                btn: btnType.ok
            },
            error: {
                title: "错误",
                icon: "-48px -48px", //红色叉
                btn: btnType.ok
            },
            confirm: {
                title: "提示",
                icon: "-48px 0", //黄色问号
                btn: btnType.okcancel
            },
            warning: {
                title: "警告",
                icon: "0 -96px", //黄色叹号
                btn: btnType.okcancel
            },
            input: {
                title: "输入",
                icon: "",
                btn: btnType.ok
            },
            custom: {
                title: "",
                icon: "",
                btn: btnType.ok
            }
        };
        var itype = type ? type instanceof Object ? type : popType[type] || {} : {}; //格式化输入的参数:弹窗类型
        var config = $.extend(true, {
            //属性
            title: "", //自定义的标题
            icon: "", //图标
            btn: btnType.ok, //按钮,默认单按钮
            //事件
            onOk: $.noop, //点击确定的按钮回调
            onCancel: $.noop, //点击取消的按钮回调
            onClose: $.noop //弹窗关闭的回调,返回触发事件
        }, itype, options);

        var $txt = $("<p>").html(popHtml); //弹窗文本dom
        var $tt = $("<span>").addClass("tt").text(config.title); //标题
        var icon = config.icon;
        var $icon = icon ? $("<div>").addClass("bigIcon").css("backgroundPosition", icon) : "";
        var btn = config.btn; //按钮组生成参数

        var popId = creatPopId(); //弹窗索引

        var $box = $("<div>").addClass("xcConfirm"); //弹窗插件容器
        var $layer = $("<div>").addClass("xc_layer"); //遮罩层
        var $popBox = $("<div>").addClass("popBox"); //弹窗盒子
        var $ttBox = $("<div>").addClass("ttBox"); //弹窗顶部区域
        var $txtBox = $("<div>").addClass("txtBox"); //弹窗内容主体区
        var $btnArea = $("<div>").addClass("btnArea"); //按钮区域

        var $ok = $("<a>").addClass("sgBtn").addClass("ok").text("确定"); //确定按钮
        var $cancel = $("<a>").addClass("sgBtn").addClass("cancel").text("取消"); //取消按钮
        var $input = $("<input>").addClass("inputBox"); //输入框
        var $clsBtn = $("<a>").addClass("clsBtn"); //关闭按钮

        //建立按钮映射关系
        var btns = {};

        if (options != "nobutton") {
            btns = {
                ok: $ok,
                cancel: $cancel
            };
        }

        init();

        function init() {
            //处理特殊类型input
            if (popType["input"] === itype) {
                $txt.append($input);
            }
            creatDom();
            bind();
        }

        function creatDom() {
            if (options == "nobutton") {
                $popBox.append(
                    $ttBox.append(
                        $tt
                    )
                ).append(
                    $txtBox.append($icon).append($txt)
                ).append(
                    $btnArea.append(creatBtnGroup(btn))
                );
            } else {
                $popBox.append(
                    $ttBox.append(
                        $clsBtn
                    ).append(
                        $tt
                    )
                ).append(
                    $txtBox.append($icon).append($txt)
                ).append(
                    $btnArea.append(creatBtnGroup(btn))
                );
            }
            $box.attr("id", popId).append($layer).append($popBox);
            $("body").append($box);
        }

        function bind() {
            //点击确认按钮
            $ok.click(doOk);

            //回车键触发确认按钮事件
            $(window).bind("keydown", function (e) {
                if (e.keyCode == 13) {
                    if ($("#" + popId).length == 1) {
                        doOk();
                    }
                }
            });

            //点击取消按钮
            $cancel.click(doCancel);

            //点击关闭按钮
            $clsBtn.click(doClose);
        }

        //确认按钮事件
        function doOk() {
            var $o = $(this);
            var v = $.trim($input.val());
            if ($input.is(":visible"))
                config.onOk(v);
            else
                config.onOk();
            $("#" + popId).remove();
            config.onClose(eventType.ok);
        }

        //取消按钮事件
        function doCancel() {
            var $o = $(this);
            config.onCancel();
            $("#" + popId).remove();
            config.onClose(eventType.cancel);
        }

        //关闭按钮事件
        function doClose() {
            $("#" + popId).remove();
            config.onClose(eventType.close);
            $(window).unbind("keydown");
        }

        //生成按钮组
        function creatBtnGroup(tp) {
            var $bgp = $("<div>").addClass("btnGroup");
            $.each(btns, function (i, n) {
                if (btnType[i] == (tp & btnType[i])) {
                    $bgp.append(n);
                }
            });
            return $bgp;
        }

        //重生popId,防止id重复
        function creatPopId() {
            var i = "pop_" + (new Date()).getTime() + parseInt(Math.random() * 100000); //弹窗索引
            if ($("#" + i).length > 0) {
                return creatPopId();
            } else {
                return i;
            }
        }
    };

    //按钮类型
    window.wxc.xcConfirm.btnEnum = {
        ok: parseInt("0001", 2), //确定按钮
        cancel: parseInt("0010", 2), //取消按钮
        okcancel: parseInt("0011", 2) //确定&&取消
    };

    //触发事件类型
    window.wxc.xcConfirm.eventEnum = {
        ok: 1,
        cancel: 2,
        close: 3
    };

    //弹窗类型
    window.wxc.xcConfirm.typeEnum = {
        info: "info",
        success: "success",
        error: "error",
        confirm: "confirm",
        warning: "warning",
        input: "input",
        custom: "custom"
    };

    window.alert = function (msg, type) {
        if (typeof (type) == 'undefined' || type == null || type == '') {
            window.wxc.xcConfirm(msg, "info");
        } else if (type == 'error') {
            window.wxc.xcConfirm(msg, window.wxc.xcConfirm.typeEnum.error);
        } else if (type == 'warning') {
            window.wxc.xcConfirm(msg, window.wxc.xcConfirm.typeEnum.warning);
        }
    };

    window.alertNoButton = function (msg, type) {
        if (typeof (type) == 'undefined' || type == null || type == '') {
            window.wxc.xcConfirm(msg, "info", "nobutton");
        }
    };

    window.confirm = function (msg, onOkFunction) {
        window.wxc.xcConfirm(msg, window.wxc.xcConfirm.typeEnum.confirm, {
            onOk: function () {
                if (typeof (onOkFunction) == "function") {
                    onOkFunction();
                }
            }
        });
    };

    if ($.fn.datetimepicker) {
        $.fn.datetimepicker.dates['zh-CN'] = {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            today: "今天",
            suffix: [],
            meridiem: ["上午", "下午"],
            rtl: false // 从右向左书写的语言你可以使用 rtl: true 来设置
        };

        /*$.fn.datetimepicker.dates['pt-BR'] = {
            format: 'yyyy-mm-dd hh:ii:ss'
        };*/

        $.fn.datetimepicker.defaults['language'] = 'zh-CN';
    }
})(jQuery);

(function ($) {
    $.gotop = function () {
            var gotop = '<div data-am-widget="gotop" class="am-gotop am-gotop-fixed" > <a href="#top" title="回到顶部" class="np-icon np-icon-gotop am-active"></a> </div>';
            $(gotop).appendTo('body');

            setTimeout(function () {
                $.AMUI.gotop.init();
            }, 10);
        },
        $.isFunc = function (r) {
            return typeof r === "function";
        };

    /*form表单提交事件*/
    jQuery.fn.extend({
        submit_form: function (func) {
            var requestType = $(this).attr("method") ? $(this).attr("method") : "POST";
            $(this).ajaxSubmit({
                type: requestType,
                url: $(this).attr("action"),
                dataType: 'json',
                /*async: false,*/
                error: function (request) {
                    alert("网络异常,请稍后再试！");
                    return false;
                },
                success: function (r) {
                    // r = object_htmlencode(r);
                    if ($.isFunc(func)) {
                        func.apply(this, [r]);
                    }
                }
            });
        }
    });

    jQuery.extend({
        post_event: function (url, data, func) {
            $(this).ajaxSubmit({
                type: requestType,
                url: url,
                dataType: 'json',
                error: function (request) {
                    alert("网络异常,请稍后再试！");
                    return false;
                },
                success: function (r) {
                    // r = object_htmlencode(r);
                    if ($.isFunc(func)) {
                        func.apply(this, [r]);
                    }
                }
            });
        }
    });

    /*返回顶部 20170809 WL*/
    $.fn.toTop = function (opt) {
        //variables
        var elem = this;
        var win = $(window);
        var doc = $('html, body');

        //Extended Options
        var options = $.extend({
            autohide: true,
            offset: 420,
            speed: 500,
            position: true,
            right: 30,
            bottom: 30
        }, opt);

        elem.css({
            'cursor': 'pointer'
        });

        if (options.autohide) {
            elem.css('display', 'none');
        }

        if (options.position) {
            elem.css({
                'position': 'fixed',
                'right': options.right,
                'bottom': options.bottom,
            });
        }

        elem.click(function () {
            doc.animate({
                scrollTop: 0
            }, options.speed);
        });

        win.scroll(function () {
            var scrolling = win.scrollTop();

            if (options.autohide) {
                if (scrolling > options.offset) {
                    elem.fadeIn(options.speed);
                } else elem.fadeOut(options.speed);
            }
        });
    };
}(jQuery));

/**
 * 序列化表单
 * 新增弹窗
 */
(function ($) {
    jQuery.prototype.serializeObject = function () {
        var obj = new Object();
        $.each(this.serializeArray(), function (index, param) {
            if (!(param.name in obj)) {
                obj[param.name] = param.value;
            }
        });
        return obj;
    };

    jQuery.prototype.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };

    jQuery.prototype.serializeObjectArray = function () {
        var objArray = [];
        var array = this.serializeArray();
        var serializeObj = {};
        $(array).each(function () {
            if (serializeObj[this.name]) {
                objArray.push(serializeObj);
                serializeObj = {};
            }
            serializeObj[this.name] = this.value;
        });
        objArray.push(serializeObj);
        return objArray;
    };
    _.addDialog = function (titile, btnEvents, htmlCode, htmlEvents, opts) {
        var h = this;
        if ($("#dlg").length == 0) {
            $("body").append('<div id="dlg" style="height:220px !important;"></div>');
        }
        var dlg = $("#dlg");
        var _opts = {
            title: titile,
            width: 700,
            height: "auto",
            resizable: false,
            position: {
                my: "center",
                at: "top+30%",
                of: window
            },
            modal: true,
            close: function () {
                dlg.dialog("close");
                $("#dlg").remove();
            },
            buttons: {
                "确定": function () {
                    if (btnEvents()) {
                        dlg.dialog("close");
                        $("#dlg").remove();
                    }
                },
                "取消": function () {
                    dlg.dialog("close");
                    $("#dlg").remove();
                }
            },
        };
        if (opts) {
            _opts = $.extend(_opts, opts)
        }
        dlg.dialog(_opts);
        dlg.html(htmlCode);
        if (htmlEvents) {
            htmlEvents();
        }
    };
}(jQuery));
/**
 * 2.0接口配置
 * host 请求的主机
 * url 请求的路径
 * lxx add 2018年8月27日16点06分
 * */
/*
var zjy_interface = {
    /!*host : "http://114.55.178.50:8089",*!/
    host: "https://zjy2.icve.com.cn",
    url: "/portalAPI/SchoolUserData/synUser"
};
*/


